package com.maoye.ossp.biz.statement.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.maoye.ossp.biz.statement.entity.BizStatementPospaySale;
import com.maoye.ossp.biz.statement.entity.BizStatementPospaySaleDetail;
import com.maoye.ossp.biz.statement.entity.BizStatementPospaySaleSupplierError;
import com.maoye.ossp.biz.statement.entity.BizStatementPospaySaleSupplier;
import com.maoye.ossp.biz.statement.entity.StatementOrder;
import com.maoye.ossp.biz.statement.entity.StatementOrderDetail;
import com.maoye.ossp.biz.statement.entity.StatementSales;
import com.maoye.ossp.biz.statement.entity.StatementSalesErro;
import com.maoye.ossp.biz.statement.entity.StatementSalesSelfrun;
import com.maoye.ossp.biz.statement.service.BizStatementPospaySaleDetailService;
import com.maoye.ossp.biz.statement.service.BizStatementPospaySaleSupplierService;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.common.web.Validation;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
/**
 * 专柜对账控制类
 * 
 * @author liangtao
 * 
 */

@Controller
@RequestMapping(value = "/biz/statement/pospaySaleSupplier/")
public class BizStatementPospaySaleSupplierController extends BaseController {
	@Resource
	private ISupplierService supplierService;
	
	@Resource
	private BizStatementPospaySaleSupplierService bizStatementPospaySaleSupplierService;
	
	@Resource
	private BizStatementPospaySaleDetailService bizStatementPospaySaleDetailService;
	
	@RequestMapping(value = "list")
	public String list(BizStatementPospaySaleSupplier statementPospaySaleSupplier,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		//获取登陆用户Id 
		Long userId=UserUtils.getCurrentUserId();
		//根据当前用户Id 如果是供应商 获取用户获取供应商信息
		Supplier supplier=supplierService.get(userId);
		QueryFilter queryFilter = getQuerFilter(request, statementPospaySaleSupplier);	
		//设置供应商编码
		if(supplier!=null){
			queryFilter.addFilter("supplierNo", supplier.getSupplierNo(), QueryOP.EQUAL);
		 }
	
		Page<BizStatementPospaySaleSupplier> page = (Page<BizStatementPospaySaleSupplier>) 
				bizStatementPospaySaleSupplierService.find(queryFilter);
		model.addAttribute("page", page);
		model.addAttribute("statementPospaySaleSupplier", statementPospaySaleSupplier);
		return resultPage("/biz/statement/statementPospaySaleSupplier/list", model, request);
	}
	
	
	@RequestMapping(value = "viewShopDetail")
	public String viewShopDetail(BizStatementPospaySaleSupplier bizStatementPospaySaleSupplier,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String shopNo = request.getParameter("shopNo");
		String supplierNo=request.getParameter("supplierNo");
		String saleDate=request.getParameter("saleDate");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String barCode=bizStatementPospaySaleSupplier.getBarCode();
		bizStatementPospaySaleSupplier.setShopNo(shopNo);
		bizStatementPospaySaleSupplier.setSupplierNo(supplierNo);
		try {
			bizStatementPospaySaleSupplier.setSaleDate(format.parse(saleDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map map=new HashMap();
		map.put("barCode",barCode);
		map.put("shopNo",shopNo);
		map.put("supplierNo", supplierNo);
		map.put("saleDate", saleDate);
		String total = "合计";
		double totalMoney = 0;
		List<BizStatementPospaySaleSupplier> bizStatementPospaySaleSupplierList=bizStatementPospaySaleSupplierService.viewShopDetail(map);
		if(bizStatementPospaySaleSupplierList!=null){
		for(BizStatementPospaySaleSupplier pospaySaleSupplier :bizStatementPospaySaleSupplierList){
			totalMoney=totalMoney+pospaySaleSupplier.getSaleAmount();
		  }
		}
		BizStatementPospaySaleSupplier bizSaleSupplier=new BizStatementPospaySaleSupplier();
		bizSaleSupplier.setShopName(total);
		bizSaleSupplier.setSaleAmount(totalMoney);
		bizSaleSupplier.setSaleDate(null);
		bizStatementPospaySaleSupplierList.add(bizSaleSupplier);
		model.addAttribute("bizStatementPospaySaleSupplierList",bizStatementPospaySaleSupplierList);
		model.addAttribute("statementPospaySaleSupplier",bizStatementPospaySaleSupplier);
		return "/biz/statement/statementPospaySaleSupplier/viewShopDetail";
	}
	
	@RequestMapping(value = "printShopDetail")
	public String printShopDetail(BizStatementPospaySaleSupplier bizStatementPospaySaleSupplier,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String shopNo = request.getParameter("shopNo");
		String supplierNo=request.getParameter("supplierNo");
		String saleDate=request.getParameter("saleDate");
		String barCode=request.getParameter("barCode");
		Map map=new HashMap();
		map.put("barCode",barCode);
		map.put("shopNo",shopNo);
		map.put("supplierNo", supplierNo);
		map.put("saleDate", saleDate);
		String total = "合计";
		double totalMoney = 0;
		List<BizStatementPospaySaleSupplier> bizStatementPospaySaleSupplierList=bizStatementPospaySaleSupplierService.viewShopDetail(map);
		if(bizStatementPospaySaleSupplierList!=null){
		for(BizStatementPospaySaleSupplier pospaySaleSupplier :bizStatementPospaySaleSupplierList){
			totalMoney=totalMoney+pospaySaleSupplier.getSaleAmount();
		  }
		}
		bizStatementPospaySaleSupplier.setShopName(total);
		bizStatementPospaySaleSupplier.setSaleAmount(totalMoney);
		bizStatementPospaySaleSupplier.setSaleDate(null);
		bizStatementPospaySaleSupplierList.add(bizStatementPospaySaleSupplier);
		model.addAttribute("bizStatementPospaySaleSupplierList",bizStatementPospaySaleSupplierList);
		return "/biz/statement/statementPospaySaleSupplier/printShopDetail";
	}
	
	
	
	@RequestMapping(value = "exportExcel")
	public void exportExcel(BizStatementPospaySaleSupplier bizStatementPospaySaleSupplier,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		//获取登陆用户Id 
		Long userId=UserUtils.getCurrentUserId();
		//根据当前用户Id 如果是供应商 获取用户获取供应商信息
		Supplier supplier=supplierService.get(userId);
		String params = request.getParameter("params");
		Map infoContent = null;
		if (Validation.isNotEmpty(params))
		{
			ObjectMapper mapper = new ObjectMapper();
			infoContent = mapper.readValue(params, Map.class);
			if(supplier!=null){
				infoContent.put("supplierNo",supplier.getSupplierNo());
			 }
		}
		else
		{
			infoContent = new HashMap();
			if(supplier!=null){
				infoContent.put("supplierNo",supplier.getSupplierNo());
			 }
		}
		try {
			// 设置输出的格式
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			//获取浏览器类型
			String user_agent = request.getHeader("User-Agent").toLowerCase();
			String fileName="";
			//为不同的浏览器，对文件名进行不同的编码转换
			if(user_agent.indexOf("firefox") > 0){
				 fileName =  new String("按门店日对账".getBytes("UTF-8"), "iso8859-1");
			}else{
				fileName = URLEncoder.encode("按门店日对账", "UTF-8");
			}
			response.setHeader("Content-disposition","attachment; filename="+fileName+".xls");
			OutputStream os = response.getOutputStream();
			bizStatementPospaySaleSupplierService.doSaveToExcel(infoContent,os);
			response.flushBuffer();
		} catch(IOException ex){
			System.out.println("导出数据出错");
		} catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
	
	
	
	
	@RequestMapping(value = "viewDetail")
	public String view(BizStatementPospaySaleDetail bizStatementPospaySaleDetail,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String shopNo = request.getParameter("shopNo");
		String barCode=request.getParameter("barCode");
		String saleDate=request.getParameter("saleDate");
		Map map=new HashMap();
		map.put("shopNo",shopNo);
		map.put("barCode", barCode);
		map.put("saleDate", saleDate);
		BizStatementPospaySaleSupplier bizStatementPospaySaleSupplier=bizStatementPospaySaleSupplierService.getBizStatementPospaySaleSupplier(map);
		QueryFilter queryFilter = getQuerFilter(request,bizStatementPospaySaleDetail);	
		queryFilter.addFilter("shopNo",shopNo, QueryOP.EQUAL);
		queryFilter.addFilter("barCode",barCode, QueryOP.EQUAL);
		queryFilter.addFilter("saleDate",saleDate, QueryOP.EQUAL);
		Page<BizStatementPospaySaleDetail> page = (Page<BizStatementPospaySaleDetail>) bizStatementPospaySaleDetailService
				.find(queryFilter);
		BizStatementPospaySaleDetail  statementPospaySaleDetail=new BizStatementPospaySaleDetail ();
		String total = "合计";
		double quantity = 0;
		double totalMoney = 0;
		List<BizStatementPospaySaleDetail> list = page.getList();
		if (list != null) {
			for (BizStatementPospaySaleDetail varStatementPospaySaleDetail : list) {
				quantity = quantity + varStatementPospaySaleDetail.getSaleNum();
				totalMoney = totalMoney + varStatementPospaySaleDetail.getSaleAmount();
			}
		}
		statementPospaySaleDetail.setBarCode(total);
		statementPospaySaleDetail.setSaleNum(quantity);
		statementPospaySaleDetail.setSaleAmount(totalMoney);
		page.getList().add(statementPospaySaleDetail);
		model.addAttribute("listSize", page.getList().size());
		model.addAttribute("bizStatementPospaySaleSupplier", bizStatementPospaySaleSupplier);
		model.addAttribute("page", page);
		return "/biz/statement/statementPospaySaleSupplier/view";
	}
	@RequestMapping(value = "{ids}/confirmChked")
	public String confirmChked(@PathVariable String ids, HttpServletRequest request,Model model,RedirectAttributes redirectAttributes) {
		String navId = request.getParameter("navId");
		redirectAttributes.addFlashAttribute(navId);
		String[] arrayStr =ids.split(",");
		for(int i=0 ;i<arrayStr.length/3;i=i+1){
			Map map=new HashMap();
			map.put("shopNo",arrayStr[i*3].toString());
			map.put("saleDate",arrayStr[i*3+1].toString());
			map.put("supplierNo",arrayStr[i*3+2].toString());
			map.put("chkFlag","03");
			bizStatementPospaySaleSupplierService.confirmChked(map);
		}
		addMessage(redirectAttributes, "确认对账成功");
		return "redirect:/biz/statement/pospaySaleSupplier/list?navId="+navId;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "addError")
	public String addError(HttpServletRequest request, Model model) {
		Map map = new HashMap();
		String shopNo = request.getParameter("shopNo");
		String barCode=request.getParameter("barCode");
		String saleDate=request.getParameter("saleDate");
		map.put("shopNo",shopNo);
		map.put("barCode", barCode);
		map.put("saleDate", saleDate);
		BizStatementPospaySaleSupplier bizStatementPospaySaleSupplier=bizStatementPospaySaleSupplierService.getBizStatementPospaySaleSupplier(map);
		BizStatementPospaySaleSupplierError bizStatementPospaySaleSupplierError = new BizStatementPospaySaleSupplierError();
		bizStatementPospaySaleSupplierError.setSaleDate(bizStatementPospaySaleSupplier.getSaleDate());
		bizStatementPospaySaleSupplierError.setSupplierNo(bizStatementPospaySaleSupplier.getSupplierNo());
		bizStatementPospaySaleSupplierError.setSupplierName(bizStatementPospaySaleSupplier.getSupplierName());
		bizStatementPospaySaleSupplierError.setShopNo(bizStatementPospaySaleSupplier.getShopNo());
		bizStatementPospaySaleSupplierError.setBarCode(bizStatementPospaySaleSupplier.getBarCode());
		bizStatementPospaySaleSupplierError.setErrorAmount(bizStatementPospaySaleSupplier.getSaleAmount());
		User user = UserUtils.getUser();
		bizStatementPospaySaleSupplierError.setCreateTime(new Date());
		bizStatementPospaySaleSupplierError.setCreateBy(String.valueOf(user.getId()));
		bizStatementPospaySaleSupplierError.setCreateByUserName(user.getName());
		model.addAttribute("bizStatementPospaySaleSupplierError",bizStatementPospaySaleSupplierError);
		return "/biz/statement/statementPospaySaleSupplierError/add";
	}
}
